/*
 * $Id: ResinInjectorFactory.java 6 2009-03-20 00:57:43Z scotthernandez $
 * $URL: https://condi-stripes.googlecode.com/svn/ConDI-Stripes/trunk/src/com/googlecode/condistripes/ResinInjectorFactory.java $
 *
 * Copyright 2008-2009 Scott Hernandez
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package com.googlecode.candistripes;

import java.lang.reflect.InvocationTargetException;

import javax.enterprise.inject.spi.BeanManager;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import net.sourceforge.stripes.util.Log;

/**
 * Finds the BeanManager no matter what server we are running on.
 * 
 * @author Scott Hernandez
 * @author Jeff Schnitzer <jeff@infohazard.org>
 */
public class BeanManagerFinder {

	/** */
    @SuppressWarnings("unused")
	private Log log = Log.getInstance(BeanManagerFinder.class);
	
    /**
     * Get the BeanManager for this server, or throw an UnsupportedOperationException
     * if one cannot be found.
     */
	@SuppressWarnings("unchecked")
	public static BeanManager getBeanManager()
	{		
		// First try Resin
		try
		{
			Class injectorClass = Class.forName("com.caucho.config.inject.InjectManager");
			return (BeanManager)injectorClass.getDeclaredMethod("create").invoke(null);
		}
		catch (ClassNotFoundException cnfe) {}
		catch (InvocationTargetException ite) {}
		catch (IllegalAccessException iae) {}
		catch (NoSuchMethodException nsme) {}
		
		// Now try the official standard
		try {
			return lookup("java:comp/BeanManager");
		}
		catch (NamingException ex) {}
		catch (ClassCastException ex) {}

		// At least one version of JBoss is like this
		try {
			return lookup("java:comp/Manager");
		}
		catch (NamingException ex) {}
		catch (ClassCastException ex) {}
		
		// At least one version of Open Webbeans is like this
		try {
			return lookup("java:app/Manager");
		}
		catch (NamingException ex) {}
		catch (ClassCastException ex) {}
		
		throw new UnsupportedOperationException("Unable to find JSR299 BeanManager");
	}

	/** */
	protected static BeanManager lookup(String jndi) throws NamingException
	{
		Context c = new InitialContext();
		return (BeanManager)c.lookup(jndi);
	}
}